package com.lh.api.controller.user;

import com.lh.api.annotation.Login;
import com.lh.api.config.MyConstants;
import com.lh.api.controller.AbstractController;
import com.lh.api.form.RecordForm;
import com.lh.api.form.UserForm;
import com.lh.api.service.UserRecordService;
import com.lh.api.service.UserService;
import com.lh.api.vo.UserInfoVo;
import com.lh.common.entity.admin.User;
import com.lh.common.entity.admin.UserRecord;
import com.lh.common.utils.RedisUtils;
import com.lh.common.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 个人信息模块
 *
 * @author gze
 * @date: 2020/5/13 0013 14:18
 */
@RestController
@RequestMapping("/api/user")
@Api(value="UserController",tags={"个人信息"})
public class UserController extends AbstractController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("info")
    @ApiOperation("获取用户信息")
    @Login
    public Result<UserInfoVo> info() {
        User userEntity = getUser();

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setName(userEntity.getName());
        userInfoVo.setPhone(userEntity.getPhone());
        userInfoVo.setUserAddress(userService.getDefaultAddress(userEntity.getUid()));
        return Result.ok(userInfoVo);
    }

    /**
     * 更新個人信息
     */
    @ApiOperation(value = "更新個人信息")
    @PostMapping("/updateOvmalUser")
    @Login
    public Result<String> updateOvmalUser(@RequestBody @Validated UserForm userForm){
        Long userId = getUserId();
        User user = new User();
        user.setUid(userId);
        user.setName(userForm.getName());
        int result = userService.updateByKey(user);

        if(result > -1){
            String userkey = String.format(MyConstants.USER_INFO_CACHE,getToken());
            User temp = getUser();
            temp.setName(userForm.getName());
            redisUtils.set(userkey,temp,redisUtils.getExpire(userkey));
        }
        return Result.ok();
    }

    /**
     * 用户点击记录
     */
    @ApiOperation(value = "用户点击记录")
    @PostMapping("/addRecord")
    public Result<String> addRecord(@RequestBody @Validated RecordForm recordForm){
        UserRecord userRecord = new UserRecord();
        userRecord.setUserId(getUserId());
        userRecord.setEquipment(recordForm.getEquipment());
        userRecord.setIp(recordForm.getIp());
        userRecord.setCreateTime(new Date());
        userRecordService.save(userRecord);
        return Result.ok();
    }


}

